import Msgpg from './Msgpg.js';
import * as bfun from '../../core/bfun.js';
import * as fun from '../../core/fun.js';
/**
 *  用例 :
 *  var hws = new HylWSocket("localhost:8080/hjsp/ws/a/1", function(e,o) {
      console.log(e)
    })
 */
export default class HylWS_KF {


	constructor(serverurl, onReceivePg, onOpen, onClose) {
		// 0 系统消息 1用户消息 2 用户指令
		this.socket = null;
		this.messageNum = 0; //收到消息数
		this.socketConnectedEnable = true;
		this._onReceivePg = onReceivePg;
		this._onOpen = onOpen;
		this._onClose = onClose;
		if (serverurl == null || serverurl == '') return null;

		if (serverurl.startsWith('ws://'))
			this._url = serverurl;
		else
			this._url = "ws://" + serverurl;
		console.log(this._url)
	}


	//ws://localhost:8080/hjsp/wsadmin

	connect() {
		let that = this;
		if ('WebSocket' in window) {
			that.socket = new window.WebSocket(that._url);
		} else {
			if ('MozWebSocket' in window) {
				that.socket = new window.MozWebSocket(that._url);
			} else {
				console.log('当前浏览器 不支持 websocket')
				return;
			}
		}
		//收到消息
		that.socket.onmessage = function(evt) {
			that.messageNum++;
			if (that._onReceivePg && evt.data) {
				bfun.blob2Buffer(evt.data,
					function(data) {
						//console.log(data);
						while (true) {
							let pg = new Msgpg();
							if (pg.ini(data)) {
								//console.log(data,pg)
								that._onReceivePg(pg, that);
								//slice 区别于subarray ,slice 截取后并重新创建一个 ,subarray 只是一个截取窗口	
								data = data.slice(pg.length());
							} else {
								return;
							}
						}
					}
				)

			}
		};

		//连接成功
		that.socket.onopen = function(e) {
			console.log("连接开启!", e)
			if (that._onOpen)
				that._onOpen(e, that);
		};
		//连接成功
		that.socket.onclose = function(e) {
			if (that._onClose)
				that._onClose(e);
			console.log("连接关闭!")
		};
		// that.timer = setInterval(function() {
		// 	if (that.socketConnectedEnable) {
		// 		//console.log("ping");
		// 		that.send("hi");
		// 	}
		// }, 180000);
	}
	/**
	 * 私有函数不建议直接使用  因为 已经使用了标准协议包对象 MsgPg
	 * @param {Object} bytes
	 */
	send(bytes) {
		
		if (this.socket && this.socket.readyState == 1) {
			this.socket.send(bytes);
		} else {
			this.socket = null;
			console.log("连接已经关闭,重新连接");
			setTimeout(this.connect, 1000);
		}
	}

	/**
	 * 适用于文本内容
	 */
	sendStr(发送人, 接收人, 主题, 文本, message) {
		if (fun._IS.isEmptyString(发送人)) return;
		if (fun._IS.isEmptyString(文本) && message == null) return;
		let pg = new MsgPg(发送人, 接收人, 主题, 文本, bfun.strToUtf8Array(message));
		this.sendPg(pg);
	}
	/**
	 * 适用于图片等内容
	 */
	sendBytes(发送人, 接收人, 主题, 文本, message) {
		if (fun._IS.isEmptyString(发送人)) return;
		if (fun._IS.isEmptyString(文本) && message == null) return;
		let pg = new MsgPg(发送人, 接收人, 主题, 文本, message);
		this.sendPg(pg);
	}
	/**
	 * @param {Msgpg} pg
	 */
	sendPg(pg) {
		this.send(pg.toSendBytes());
	}


	//保持连接的方式 每隔100s  ping一下主机 如果断开重连

	//
	close() {
		console.log("关闭??")
		clearTimeout(that.timer);
		that.socket.close();
	}

};
